<template>
  <div>
    <!-- 导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!--警告区域 -->
      <el-alert
        show-icon=""
        title="注意:只允许为第三级分类设置相关参数"
        type="warning"
        :closable="false"
      >
      </el-alert>
      <!-- 选择商品分类区域 -->
      <el-row>
        <el-col class="cat_opt"
          ><span>选择商品分类: </span>
          <!-- 级联选择器 -->
          <el-cascader
            v-model="selectedCateData"
            :options="cateList"
            expand-trigger="hover"
            :props="cateProps"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- 商品分类表格-->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisables"
            @click="addDialogVisible = true"
            >添加参数</el-button
          >
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleCloed(i, scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="showEidtParams(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisables"
            @click="addDialogVisible = true"
            >添加属性</el-button
          >
          <!-- 静态参数表格 -->
          <el-table :data="onlyTabData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleCloed(i, scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="showEidtParams(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogCloed"
    >
      <el-form
        :model="addForm"
        :rules="addFormules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑参数对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="editDialogVisible"
      width="50%"
    >
      <el-form
        :model="editForm"
        :rules="addFormules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Params",
  data() {
    return {
      // 商品分类列表
      cateList: [],
      //级联选择框配置对象
      cateProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      //级联选择框双向绑定的数据
      selectedCateData: [],
      //被激活页签的名称
      activeName: "many",
      // 动态参数数据
      manyTableData: [],
      //静态参数数据
      onlyTabData: [],
      //控制添加对话框显示与隐藏
      addDialogVisible: false,
      //添加参数的表单数据对象
      addForm: {
        attr_name: "",
      },
      addFormules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" },
        ],
      },
      //控制编辑对话框的显示和隐藏
      editDialogVisible: false,
      //编辑信息
      editForm: {
        attr_id: "",
        attr_name: "",
      },
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) {
        return this.$message.err("请求失败");
      }
      this.cateList = res.data;
      console.log(this.cateList);
    },
    // 级联选择框轩中的变化，会触发这个函数
    handleChange() {
      // 级联选择器获得分类参数列表
      this.getParamsData();
    },
    // 获取分类参数列表
    async getParamsData() {
      //选中的不是三级分类
      if (this.selectedCateData.length !== 3) {
        this.selectedCateData = [];
        // this.manyTableData = [];
        // this.onlyTabData = [];
        return;
      }
      console.log(this.selectedCateData);
      //   选中的是三级分类
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName },
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.err("请求参数列表失败");
      }
      //console.log(res.data);
      //将attr_vals分割
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        //文本框的显示与隐藏
        item.inputVisible = false;
        //输入值
        item.inputValue = "";
      });

      console.log(res.data);
      if (this.activeName == "many") {
        this.manyTableData = res.data;
      } else {
        this.onlyTabData = res.data;
      }
    },
    // tab页签点击事件的处理函数
    handleClick() {
      // 点击页签是获得参数分类列表
      this.getParamsData();
      console.log(this.activeName);
    },
    //监听添加数据框的关闭事件
    addDialogCloed() {
      this.$refs.addFormRef.resetFields();
    },
    //点击按钮，添加参数
    addParams() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;

        //验证成功
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName,
          }
        );
        if (res.meta.status !== 201) {
          return this.$message.err("添加失败");
        }
        this.addDialogVisible = false;
        this.getParamsData();
      });
    },
    //控制对话框的显示与隐藏
    async showEidtParams(id) {
      //拿到对应行的id
      console.log(id);
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${id}`,
        { params: this.activeName }
      );
      if (res.meta.status !== 200) {
        return this.$message.err("获取参数失败");
      }
      this.editForm = res.data;

      this.editDialogVisible = true;
    },
    // 点击修改参数名称
    editParams() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;

        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          { attr_name: this.editForm.attr_name, attr_sel: this.activeName }
        );
        if (res.meta.status !== 200) {
          return this.$message.err("更改信息失败");
        }
        this.$message.success("更改信息成功");
        this.getParamsData();
        this.editDialogVisible = false;
      });
    },

    //删除参数或属性
    async removeParams(id) {
      const confirmResoult = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmResoult !== "confirm") {
        return this.$message.info("取消删除");
      }

      console.log(confirmResoult);

      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${id}`
      );
      if (res.meta.status !== 200) {
        return this.$message.err("删除失败");
      }
      this.$message.success("删除成功");
      this.getParamsData();
    },
    //文本框失去焦点，或摁下enter键会触发
    async handleInputConfirm(row) {
      console.log("ok");
      row.inputVisible = false;
      //
      if (row.inputValue.trim().length === 0) {
        row.inputValue = "";
        row.inputVisible = false;
        return;
      }
      //如果没有return，则证明输入内容，需要做下一步处理
      row.attr_vals.push(row.inputValue.trim());
      //清空数据
      row.inputValue = "";
      //隐藏
      row.inputVisible = false;
      //发起请求 保存在数据库
      this.saveAttrVald(row);
    },
    //保存新的标签到数据库中
    async saveAttrVald(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(" "),
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.err("修改参数失败");
      }
      this.$message.success("修改参数成功");
    },
    showInput(row) {
      row.inputVisible = true;
      //自动获取焦点
      //$nextTick:当页面上的元素被重新渲染之后， 才会指定回调函数中的代码
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    //删除标签
    handleCloed(i, row) {
      //删除索引为i的项
      row.attr_vals.splice(i, 1);
      this.saveAttrVald(row);
    },
  },
  computed: {
    //如果按钮需要被禁用，则返回true，否则返回false
    isBtnDisables() {
      if (this.selectedCateData.length !== 3) {
        return true;
      }
      return false;
    },
    // 获得三级分类的id
    cateId() {
      if (this.selectedCateData.length === 3) {
        return this.selectedCateData[2];
      }
      return null;
    },
    // 动态激活标题文本
    titleText() {
      if (this.activeName === "many") {
        return "动态参数";
      }
      return "静态属性";
    },
  },
};
</script>

<style lang="less" scoped>
.cat_opt {
  margin-top: 15px;
  width: 200px;
  span {
    float: left;
  }
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 120px;
}
</style>